//
//  SellerView.m
//  yunbaolive
//
//  Created by ybRRR on 2020/1/16.
//  Copyright © 2020 cat. All rights reserved.
//

#import "SellerView.h"
#import "ShopInfoVC.h"
#import "BillManageVC.h"
#import "SellerOrderManagementVC.h"
#import "CommodityManagementVC.h"
#import "AddressVC.h"
#import "AddCommodityVC.h"
#import "AddGoodsVC.h"
#import "ClassificationVC.h"
#import "ClassToExamineVC.h"
#import "PlatformGoodsVC.h"
@implementation SellerView
-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self creatUI];
        [self creatSectionOne];
        [self creatSectionTwo];
        [self creatSectionThree];
//        [self getUnreadCount];
    }
    return self;
}
#pragma mark -----数据请求-------------
-(void)requstData{
    YBWeakSelf;
    NSDictionary *signdic = @{@"uid":[Config getOwnID],@"token":[Config getOwnToken], @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]]};
    NSString *sign = [PublicObj sortString:signdic];

    NSDictionary *dic = @{
                          @"uid":[Config getOwnID],
                          @"token":[Config getOwnToken],
                          @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]],
                          @"sign":sign
                          };
    [WYNetworking postWithUrl:@"Seller.getHome" Dic:dic Suc:^(int code, id info, NSString *msg) {
        if (code ==0) {
            NSDictionary *infos = [info firstObject];
            shopInfo = [infos valueForKey:@"shop_info"];
            [weakSelf reloadData:infos];
        }else{
            [MBProgressHUD showError:msg];
        }
    } Fail:^(id fail) {
        
    }];
}
-(void)reloadData:(NSDictionary *)infos{
    NSString *point = minstr([[infos valueForKey:@"shop_info"] valueForKey:@"composite_points"]);
    NSString *ptStr = YZMsg(@"综合分");
    NSString *composite_points = [NSString stringWithFormat:@"%@ \n %@",point,ptStr];
    NSRange redRange = NSMakeRange(0, composite_points.length-ptStr.length);
    NSMutableAttributedString *contentStr = [[NSMutableAttributedString alloc] initWithString:composite_points];
    [contentStr addAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor],NSFontAttributeName:[UIFont boldSystemFontOfSize:14]} range:redRange];

    [scoreBtn setAttributedTitle:contentStr forState:0];
    
    NSString *balance = minstr([[infos valueForKey:@"balance_info"] valueForKey:@"balance"]);
    NSString *balance_total = minstr([[infos valueForKey:@"balance_info"] valueForKey:@"balance_total"]);

    //账户余额
    NSString *str = [NSString stringWithFormat:@"%@\n%@",priceTitleArr[0],balance];
    NSMutableAttributedString *balanceStr = [[NSMutableAttributedString alloc] initWithString:str];
    NSRange redRangesss = [str rangeOfString:balance];
    [balanceStr addAttributes:@{NSForegroundColorAttributeName:Pink_Cor,NSFontAttributeName:[UIFont boldSystemFontOfSize:16]} range:redRangesss];
    if ([str hasSuffix:@".00"]) {
          [balanceStr addAttributes:@{NSFontAttributeName:SYS_Font(11)} range:NSMakeRange(str.length-3, 3)];
      }
    [balanceBtn setAttributedTitle:balanceStr forState:0];

    //全部收入
    NSString *totalstr = [NSString stringWithFormat:@"%@\n%@",priceTitleArr[1],balance_total];
    NSMutableAttributedString *balanceTotalStr = [[NSMutableAttributedString alloc] initWithString:totalstr];
    NSRange redRangebbb = [totalstr rangeOfString:balance_total];
    [balanceTotalStr addAttributes:@{NSForegroundColorAttributeName:Pink_Cor,NSFontAttributeName:[UIFont boldSystemFontOfSize:16]} range:redRangebbb];
    if ([totalstr hasSuffix:@".00"]) {
          [balanceTotalStr addAttributes:@{NSFontAttributeName:SYS_Font(11)} range:NSMakeRange(totalstr.length-3, 3)];
      }
    [allIncomeBtn setAttributedTitle:balanceTotalStr forState:0];
    //待付款
    NSString *waitPay =minstr([[infos valueForKey:@"order_info"] valueForKey:@"wait_payment"]);
    [waitPayBtn setTitle:[NSString stringWithFormat:@"%@ \n %@",waitPay,orderTitleArr[0]] forState:0];

    //待发货
    NSString *waitSend =minstr([[infos valueForKey:@"order_info"] valueForKey:@"wait_shipment"]);
    [waitSendBtn setTitle:[NSString stringWithFormat:@"%@ \n %@",waitSend,orderTitleArr[1]] forState:0];

    //待退款
    NSString *waitRefund =minstr([[infos valueForKey:@"order_info"] valueForKey:@"wait_refund"]);
    [waitRefundBtn setTitle:[NSString stringWithFormat:@"%@ \n %@",waitRefund,orderTitleArr[2]] forState:0];

    
    sellerInfoLb.text = minstr([infos valueForKey:@"seller_desc"]);
}
-(void)creatUI{
    
    
    headImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, _window_width, 190)];
    headImg.userInteractionEnabled = YES;
    headImg.image = [UIImage imageNamed:@"sellerBackground"];
    [self addSubview:headImg];

    UIImageView *avatarImg = [[UIImageView alloc]init];
    [avatarImg sd_setImageWithURL:[NSURL URLWithString:[Config getUserAvatar]]];
    avatarImg.layer.cornerRadius = 25;
    avatarImg.layer.masksToBounds = YES;
    [self addSubview:avatarImg];
    [avatarImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self).offset(34+statusbarHeight+20+15);
        make.width.height.mas_equalTo(50);
        make.left.equalTo(self).offset(20);
    }];
    
    UIButton *nameBtn = [UIButton buttonWithType:0];
    nameBtn.titleLabel.font =[UIFont boldSystemFontOfSize:15];
    [nameBtn setTitleColor:[UIColor whiteColor] forState:0] ;
    [nameBtn setTitle:[Config getOwnNicename] forState:0];
    [nameBtn addTarget:self action:@selector(shopInfoClick:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:nameBtn];
    [nameBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(avatarImg.mas_right).offset(10);
        make.top.equalTo(avatarImg.mas_top).offset(5);
        make.height.mas_equalTo(15);
    }];
    
    UIImageView *rightimg = [[UIImageView alloc]init];
    rightimg.image = [UIImage imageNamed:@"shop_right"];
    [self addSubview:rightimg];
    [rightimg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(nameBtn.mas_right).offset(10);
        make.width.height.mas_equalTo(18);
        make.centerY.equalTo(nameBtn);
    }];
    
    sellerInfoLb= [[UILabel alloc]init];
    sellerInfoLb.font = [UIFont systemFontOfSize:13];
    sellerInfoLb.textColor = [UIColor grayColor];
    sellerInfoLb.text = YZMsg(@"暂无信息");
    sellerInfoLb.numberOfLines = 0;
    [self addSubview:sellerInfoLb];
    [sellerInfoLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(nameBtn);
        make.top.equalTo(nameBtn.mas_bottom).offset(10);
        //make.height.mas_equalTo(16);
        make.right.lessThanOrEqualTo(self.mas_right).offset(-80);
    }];
    
    UIButton *infoBtn = [UIButton buttonWithType:0];
    [infoBtn addTarget:self action:@selector(shopInfoClick:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:infoBtn];
    [infoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(nameBtn.mas_left);
        make.top.equalTo(nameBtn.mas_top);
        make.right.equalTo(rightimg.mas_right);
        make.bottom.equalTo(sellerInfoLb.mas_bottom);
    }];
    
    
    UIImageView *scoreImg = [[UIImageView alloc]init];
    scoreImg.layer.borderColor = [UIColor whiteColor].CGColor;
    scoreImg.layer.borderWidth = 1;
    scoreImg.layer.cornerRadius = 28;
    scoreImg.layer.masksToBounds = YES;
    scoreImg.backgroundColor = [UIColor clearColor];
    [self addSubview:scoreImg];
    [scoreImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(56);
        make.centerY.equalTo(avatarImg);
        make.right.equalTo(self).offset(-20);
    }];
    
    scoreBtn = [UIButton buttonWithType:0];
    [scoreBtn setBackgroundColor:[UIColor whiteColor]];
    [scoreBtn setTitleColor:[UIColor blackColor] forState:0];
    scoreBtn.titleLabel.font = [UIFont systemFontOfSize:10];
    scoreBtn.titleLabel.numberOfLines = 0;
    scoreBtn.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
    scoreBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    scoreBtn.layer.cornerRadius = 25;
    [self addSubview:scoreBtn];
    [scoreBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(50);
        make.center.equalTo(scoreImg);
    }];
}
-(void)creatSectionOne{
    backView1 = [[UIView alloc]init];
    backView1.frame = CGRectMake(15, headImg.bottom-35, _window_width-30, 70);
    backView1.backgroundColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0];
    backView1.layer.cornerRadius = 5;
    backView1.layer.masksToBounds = YES;
    backView1.layer.shadowColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.05].CGColor;
    backView1.layer.shadowOffset = CGSizeMake(0,0);
    backView1.layer.shadowOpacity = 1;
    backView1.layer.shadowRadius = 3;
    [self addSubview:backView1];
    
    priceTitleArr = @[YZMsg(@"账户余额 (元)"),YZMsg(@"累计收入 (元)")];
    NSArray *scoreArr = @[@"0.00",@"0.00"];
    for (int i = 0; i < priceTitleArr.count; i ++) {
        UIButton *btn = [UIButton buttonWithType:0];
        btn.frame = CGRectMake(i *backView1.width/2+10, 10, backView1.width/2-20, 50);
        btn.titleLabel.font = [UIFont systemFontOfSize:14];
        btn.titleLabel.textAlignment = NSTextAlignmentLeft;
        btn.titleLabel.numberOfLines = 0;
        btn.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
        NSString *title = priceTitleArr[i];
        NSString *score = scoreArr[i];
        NSString *str = [NSString stringWithFormat:@"%@ \n %@",title,score];
        NSMutableAttributedString *contentStr = [[NSMutableAttributedString alloc] initWithString:str];
        NSRange redRange = NSMakeRange(title.length, str.length-title.length);
        [contentStr addAttributes:@{NSForegroundColorAttributeName:Pink_Cor,NSFontAttributeName:[UIFont boldSystemFontOfSize:16]} range:redRange];
        [btn setAttributedTitle:contentStr forState:0];
        [btn addTarget:self action:@selector(billClick) forControlEvents:UIControlEventTouchUpInside];
        [backView1 addSubview:btn];
        if (i == 0) {
           balanceBtn  = btn;
        }else{
           allIncomeBtn  = btn;
        }

    }
}
-(void)creatSectionTwo{
    backView2 = [[UIView alloc]initWithFrame:CGRectMake(15, backView1.bottom+10, _window_width-30, 120)];
    backView2.backgroundColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0];
    backView2.layer.shadowColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.05].CGColor;
    backView2.layer.shadowOffset = CGSizeMake(0,0);
    backView2.layer.shadowOpacity = 1;
    backView2.layer.shadowRadius = 3;
    backView2.layer.cornerRadius = 5;
    [self addSubview:backView2];
    
    UILabel *orderTitle = [[UILabel alloc]init];
    orderTitle.frame = CGRectMake(15, 15, 180, 18);
    orderTitle.text =YZMsg(@"订单管理");
    orderTitle.font = [UIFont boldSystemFontOfSize:14];
    orderTitle.textColor = [UIColor blackColor];
    [backView2 addSubview:orderTitle];
    
    UIButton *allOrderBtn = [UIButton buttonWithType:0];
    allOrderBtn.frame = CGRectMake(backView2.width-110, 15, 110, 18);
    [allOrderBtn setTitleColor:RGB(200, 200, 200) forState:0];
    [allOrderBtn setTitle:YZMsg(@"查看全部订单") forState:0];
    [allOrderBtn setImage:[UIImage imageNamed:@"shop_right"] forState:0];
    allOrderBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [allOrderBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, - allOrderBtn.imageView.image.size.width, 0, allOrderBtn.imageView.image.size.width)];
    [allOrderBtn setImageEdgeInsets:UIEdgeInsetsMake(0, allOrderBtn.titleLabel.bounds.size.width, 0, -allOrderBtn.titleLabel.bounds.size.width)];
    allOrderBtn.tag = 10009;
    [allOrderBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];

    [backView2 addSubview:allOrderBtn];
    
    orderTitleArr = @[YZMsg(@"待付款"),YZMsg(@"待发货"),YZMsg(@"等待退款")];
    for (int i = 0; i < orderTitleArr.count; i ++) {
        UIButton *btn = [UIButton buttonWithType:0];
        btn.frame = CGRectMake(i *backView2.width/4, orderTitle.bottom +18, backView1.width/4, 50);
        [btn setTitle:[NSString stringWithFormat:@"%@ \n %@",@"0",orderTitleArr[i]] forState:0];
        [btn setTitleColor:[UIColor blackColor] forState:0];
        btn.titleLabel.font = [UIFont boldSystemFontOfSize:12];
        btn.titleLabel.numberOfLines = 0;
        btn.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
        btn.titleLabel.textAlignment = NSTextAlignmentCenter;
        btn.tag = 20000+i;
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];

        [backView2 addSubview:btn];
        if (i == 0) {
            waitPayBtn= btn ;
        }else if (i == 1){
            waitSendBtn = btn ;
        }else{
           waitRefundBtn = btn;
        }
    }



}
-(void)creatSectionThree{
    UIView *backView3 = [[UIView alloc]initWithFrame:CGRectMake(15, backView2.bottom+10, _window_width-30, 70)];
    backView3.backgroundColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0];
    backView3.layer.shadowColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.05].CGColor;
    backView3.layer.shadowOffset = CGSizeMake(0,0);
    backView3.layer.shadowOpacity = 1;
    backView3.layer.shadowRadius = 3;
    backView3.layer.cornerRadius = 5;
    [self addSubview:backView3];
    
    NSArray *imgeTitle = @[@"添加商品",@"商品管理",@"地址管理",@"经营类别"];

    NSArray *title2Arr = @[YZMsg(@"添加商品"),YZMsg(@"商品管理"),YZMsg(@"地址管理"),YZMsg(@"经营类别")];//YZMsg(@"消息"),
    for (int i = 0; i < title2Arr.count; i ++) {
        UIButton *btn = [UIButton buttonWithType:0];
//        if (i < 4) {
            btn.frame = CGRectMake(i *backView3.width/4, 10, backView3.width/4, 50);
//        }else{
//            btn.frame = CGRectMake(0, 70, backView3.width/4, 50);
//
//        }
        [btn setTitle:title2Arr[i] forState:0];
        [btn setTitleColor:[UIColor blackColor] forState:0];
        btn.titleLabel.font = [UIFont systemFontOfSize:12];
        btn.imageView.contentMode = UIViewContentModeScaleAspectFit;
        [btn setImage:[UIImage imageNamed:[NSString stringWithFormat:@"shop_%@",imgeTitle[i]]] forState:0];
        btn = [PublicObj setUpImgDownText:btn];
        btn.tag = 30000+i;
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];

        [backView3 addSubview:btn];
        
//        if (i == 3) {
//            msgTaglb= [[UILabel alloc]init];
//            msgTaglb.frame = CGRectMake(btn.width/2+10, 0, 12, 12);
//            msgTaglb.backgroundColor = [UIColor redColor];
//            msgTaglb.layer.cornerRadius = 6;
//            msgTaglb.layer.masksToBounds = YES;
//            msgTaglb.textColor = [UIColor whiteColor];
//            msgTaglb.textAlignment = NSTextAlignmentCenter;
//            msgTaglb.font = [UIFont systemFontOfSize:8];
//            [btn addSubview:msgTaglb];
//            msgTaglb.hidden = YES;
//        }
    }

}
-(void)btnClick:(UIButton *)sender{
    switch (sender.tag) {
        case 10009:{
            SellerOrderManagementVC *order = [[SellerOrderManagementVC alloc]init];
            order.selectIndex = 3;
            [[YBBaseAppDelegate sharedAppDelegate]pushViewController:order animated:YES];
        }

        break;
        //待付款
        case 20000:{
            SellerOrderManagementVC *order = [[SellerOrderManagementVC alloc]init];
            order.selectIndex = 2;
            [[YBBaseAppDelegate sharedAppDelegate]pushViewController:order animated:YES];
        }

            break;
        //待发货
        case 20001:{
            SellerOrderManagementVC *order = [[SellerOrderManagementVC alloc]init];
            order.selectIndex = 0;
            [[YBBaseAppDelegate sharedAppDelegate]pushViewController:order animated:YES];
        }

            break;
        //等待退款
        case 20002:{
            SellerOrderManagementVC *order = [[SellerOrderManagementVC alloc]init];
            order.selectIndex = 1;
            [[YBBaseAppDelegate sharedAppDelegate]pushViewController:order animated:YES];
        }
            break;

        //添加商品
        case 30000:{
            YBWeakSelf;
            NSArray *arr = @[YZMsg(@"平台商品"),YZMsg(@"站内商品"),YZMsg(@"站外商品")];
            
            if ([PublicObj isUp]) {
                arr = @[YZMsg(@"平台商品"),YZMsg(@"编辑新商品")];
            }
            
            _actionSheet = [[YBAlertActionSheet alloc]initWithFrame:CGRectMake(0, 0, _window_width, _window_height) cancelTitle:YZMsg(@"取消") cancelColor:[UIColor blackColor]  andRowHeight:50 andOtherTitle:arr];
            
            _actionSheet.btnEvent = ^(NSString *btnTitle) {
                NSString *titleStr = btnTitle;
                if ([titleStr isEqual:YZMsg(@"取消")]) {
                    [weakSelf.actionSheet removeFromSuperview];
                    weakSelf.actionSheet = nil;
                }else if ([titleStr isEqual:YZMsg(@"站内商品")] || [titleStr isEqual:YZMsg(@"编辑新商品")]) {
                    [weakSelf.actionSheet removeFromSuperview];
                    weakSelf.actionSheet = nil;

                    AddCommodityVC *add = [[AddCommodityVC alloc]init];
                    [[YBBaseAppDelegate sharedAppDelegate]pushViewController:add animated:YES];
                }else if ([titleStr isEqual:YZMsg(@"站外商品")]) {
                    [weakSelf.actionSheet removeFromSuperview];
                    weakSelf.actionSheet = nil;

                    AddGoodsVC *vc = [[AddGoodsVC alloc]init];
                    [[YBBaseAppDelegate sharedAppDelegate] pushViewController:vc animated:YES];
                }else if ([titleStr isEqual:YZMsg(@"平台商品")]) {
                    [weakSelf.actionSheet removeFromSuperview];
                    weakSelf.actionSheet = nil;

                    PlatformGoodsVC *platgoods = [[PlatformGoodsVC alloc]init];
                    [[YBBaseAppDelegate sharedAppDelegate] pushViewController:platgoods animated:YES];
                }
            };
            [self addSubview:_actionSheet];
        }
            break;

        //商品管理
        case 30001:{
            CommodityManagementVC *commodity = [[CommodityManagementVC alloc]init];
            [[YBBaseAppDelegate sharedAppDelegate]pushViewController:commodity animated:YES];
        }
            break;

        //地址管理
        case 30002:{
            AddressVC *address = [[AddressVC alloc]init];
            address.titleStr =  YZMsg(@"退货地址管理");
            [[YBBaseAppDelegate sharedAppDelegate]pushViewController:address animated:YES];
        }
            break;

//        //消息
//        case 30003:{
//            MessageListVC *MC = [[MessageListVC alloc]init];
//            [[YBBaseAppDelegate sharedAppDelegate]pushViewController:MC animated:YES];
//        }

            break;
        //经营类别
        case 30003:{
            [self getCategoryStatus];
        }

        break;

        default:
            break;
    }

}

#pragma mark-----账单管理-------
-(void)billClick{
    BillManageVC *bill = [[BillManageVC alloc]init];
    [[YBBaseAppDelegate sharedAppDelegate]pushViewController:bill animated:YES];
}
#pragma mark-----小店详情-------
-(void)shopInfoClick:(UIButton *)sender{
    ShopInfoVC *shop = [[ShopInfoVC alloc]init];
    shop.shopInfoDic = shopInfo;
    [[YBBaseAppDelegate sharedAppDelegate]pushViewController:shop animated:YES];
}

#pragma mark----获取经营类目状态---------
-(void)getCategoryStatus{

    NSDictionary *dic = @{
                          @"uid":[Config getOwnID],
                          @"token":[Config getOwnToken],
                          };
    
    [WYNetworking postWithUrl:@"Shop.getApplyBusinessCategory" Dic:dic Suc:^(int code, id info, NSString *msg) {
        if (code ==0) {
            NSDictionary *infos = [info firstObject];
            //['status'] 0（审核中） 1（审核通过和未提交过申请）   2（审核失败）
            if ([minstr([infos valueForKey:@"status"]) isEqual:@"1"]) {
                ClassificationVC *classVc = [[ClassificationVC alloc]init];
                [[YBBaseAppDelegate sharedAppDelegate]pushViewController:classVc animated:YES];
            }else {
                ClassToExamineVC *examine = [[ClassToExamineVC alloc]init];
                examine.statusStr =minstr([infos valueForKey:@"status"]);
                examine.reasonStr =minstr([infos valueForKey:@"reason"]);
                [[YBBaseAppDelegate sharedAppDelegate]pushViewController:examine animated:YES];
            }
        }else{
            [MBProgressHUD showError:msg];
        }

        } Fail:^(id fail) {
            
        }];


}
@end
